package com.fenrirtec.aepp.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.portal.common.definition.Definition;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginCheckInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(LoginCheckInterceptor.class);
	
	private static final String TIMEOUT = "timeout";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpSession session = ServletActionContext.getRequest().getSession();
		
		HttpServletRequest req = ServletActionContext.getRequest();
        String path = req.getRequestURI().substring(7);
        String queryString = req.getQueryString();
        if (queryString == null) {
            queryString = "";
        }
        String realPath = path + (StringUtils.isNotEmpty(queryString) ? "?" : "") + queryString;
        if (realPath.toLowerCase().startsWith("/forward/") && realPath.indexOf("/forward/login") < 0 && realPath.indexOf("/forward/auth") < 0 && realPath.indexOf("/forward/logout") < 0) {
            session.setAttribute("prePage", realPath.replaceFirst("/forward/", ""));
        }

		if (session == null || session.getAttribute(Definition.SessionKey.MEMBER_INFO) == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("user does not login.");
			}
			return TIMEOUT;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("user already login. session=" + session);
			}
			return invocation.invoke();
		}
	}
}
